package com.wkg.lotterysystem.controller;


import com.wkg.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.wkg.lotterysystem.common.exception.ControllerException;
import com.wkg.lotterysystem.common.pojo.CommonResult;
import com.wkg.lotterysystem.common.utils.JacksonUtils;
import com.wkg.lotterysystem.common.utils.RedisUtil;
import com.wkg.lotterysystem.controller.param.UserShortMessageLoginParam;
import com.wkg.lotterysystem.controller.param.UserPasswordLoginParam;
import com.wkg.lotterysystem.controller.param.UserRegisterParam;
import com.wkg.lotterysystem.controller.result.BaseUserInfoResult;
import com.wkg.lotterysystem.controller.result.UserLoginResult;
import com.wkg.lotterysystem.controller.result.UserRegisterResult;
import com.wkg.lotterysystem.service.dto.UserLoginDTO;
import com.wkg.lotterysystem.service.dto.UserDTO;
import com.wkg.lotterysystem.service.dto.UserRegisterDTO;
import com.wkg.lotterysystem.service.UserService;
import com.wkg.lotterysystem.service.VerificationCodeService;
import com.wkg.lotterysystem.service.enums.UserIdentityEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户控制器类
 * 处理与用户相关的HTTP请求，如用户注册等
 */
@RestController
public class UserController {
    // 使用SLF4J日志框架
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private RedisUtil redisUtil;

    // 自动注入用户服务
    @Autowired
    private UserService userService;

    @Autowired
    private VerificationCodeService verificationCodeService;

    /**
     * 用户注册接口
     *
     * @param param 用户注册参数，包含用户名、密码等信息
     * @return 统一返回结果CommonResult，包含注册结果信息
     * @apiNote 该接口接收JSON格式的用户注册信息，进行参数校验后完成注册
     */
    @RequestMapping("/register")
    public CommonResult<UserRegisterResult> userRegister(@Validated @RequestBody UserRegisterParam param) {
        // 日志打印：记录用户注册请求参数
        logger.info("userRegister - UserRegisterParam:{}", JacksonUtils.writeValueAsString(param));

        // 调用Service层完成用户注册业务逻辑
        UserRegisterDTO userRegisterDTO = userService.register(param);

        // 将Service返回结果转换为前端需要的格式并返回
        return CommonResult.success(convertToUserRegisterResult(userRegisterDTO));
    }

    /**
     * 发送验证码服务
     *
     * @param phoneNumber
     * @return
     */
    @RequestMapping("/verification-code/send")
    public CommonResult<Boolean> sendVerificationCode(String phoneNumber) {
        logger.info("sendVerificationCode phoneNumber:{}", phoneNumber);
        verificationCodeService.sendVerificationCode(phoneNumber);
        return CommonResult.success(Boolean.TRUE);
    }

    /**
     * 管理员通过密码登录
     *
     * @param param
     * @return
     */
    @RequestMapping("/password/login")
    public CommonResult<UserLoginResult> userPasswordLogin(@Validated @RequestBody UserPasswordLoginParam param) {
        logger.info("userPasswordLogin UserPsswordLoginParam:{}", JacksonUtils.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    /**
     * 管理员通过手机验证码登录
     *
     * @param param
     * @return
     */
    @RequestMapping("/message/login")
    public CommonResult<UserLoginResult> userMessageLogin(@Validated @RequestBody UserShortMessageLoginParam param) {
        logger.info("userMessageLogin ShortMessageLoginParam:{}", JacksonUtils.writeValueAsString(param));
        UserLoginDTO userLoginDTO = userService.login(param);
        return CommonResult.success(convertToUserLoginResult(userLoginDTO));
    }

    /**
     * 获取人员列表
     *
     * @param identity
     * @return
     */
    @RequestMapping("/base-user/find-list")
    public CommonResult<List<BaseUserInfoResult>> findBaseUserList(String identity) {
        logger.info("findBaseUserList  identity :{}", identity);
        List<UserDTO> userDTOList = userService.findUserInfo(UserIdentityEnum.forName(identity));
        return CommonResult.success(convertToList(userDTOList));
    }

    private List<BaseUserInfoResult> convertToList(List<UserDTO> userDTOList) {
        if (CollectionUtils.isEmpty(userDTOList)) {
            return Arrays.asList();
        }
        return userDTOList.stream()
                .map(userDTO -> {
                    BaseUserInfoResult result = new BaseUserInfoResult();
                    result.setUserId(userDTO.getUserId());
                    result.setUserName(userDTO.getUserName());
                    result.setIdentity(userDTO.getIdentity().name());
                    return result;
                }).collect(Collectors.toList());

    }

    /**
     * 将数据转换成Result要求的类型
     *
     * @param userLoginDTO
     * @return
     */
    private UserLoginResult convertToUserLoginResult(UserLoginDTO userLoginDTO) {
        if (userLoginDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.LOGIN_ERROR);
        }
        UserLoginResult userLoginResult = new UserLoginResult();
        userLoginResult.setIdentity(userLoginDTO.getIdentity());
        userLoginResult.setToken(userLoginDTO.getToken());
        return userLoginResult;
    }


    /**
     * 将用户注册DTO转换为前端需要的Result格式
     *
     * @param userRegisterDTO 服务层返回的用户注册数据传输对象
     * @return 前端需要的用户注册结果对象
     * @throws ControllerException 当注册DTO为null时抛出业务异常
     */
    private UserRegisterResult convertToUserRegisterResult(UserRegisterDTO userRegisterDTO) {
        UserRegisterResult result = new UserRegisterResult();

        // 参数校验：确保服务层返回的数据有效
        if (null == userRegisterDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.REGISTER_ERROR);
        }

        // 设置返回结果中的用户ID
        result.setUserId(userRegisterDTO.getUserId());
        return result;
    }


}
